package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.OrderLifecycleUtil;

public class MoneyInOrdersTimeoutCleanJob  extends GopayBaseJob{
	public static final String TRANSTYPE = "00200";
	private Logger logger = LoggerFactory
			.getLogger(MoneyInOrdersTimeoutCleanJob.class);
	private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;
	private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

	@Resource(name = "cpsGeneralMainOrderOperClient")
	public void setCpsGeneralMainOrderOperClient(
			MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
		this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
	}

	@Resource(name = "cpsGeneralMainOrderDAO")
	public void setCpsGeneralMainOrderDAO(
			CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO) {
		this.cpsGeneralMainOrderDAO = cpsGeneralMainOrderDAO;
	}

	@Override
	public void doJobInternal() {
		
		Map param = new HashMap();
		String timeSpan = OrderLifecycleUtil.getLifecycle(TRANSTYPE);
		param.put("timeSpan", timeSpan);

		int count =cpsGeneralMainOrderDAO.findTimeoutOrdersInMoneyInCount(param);
		if(count==0){
			return;
		}
		//循环次数
		int i = (count+999)/1000;
		for (int j = 0; j < i; j++) {
			//每次1000条
			List<Object> orderList = cpsGeneralMainOrderDAO
					.findTimeoutOrdersInMoneyIn(param,j*1000+1,1000);
			updateStatus(orderList);
		}
		
		
	}

	private void updateStatus(List<Object> orderList) {
		if (!(orderList.isEmpty())) {
			String txnStaCode = String
					.valueOf(TxnStaCode.TXN_STA_CD_20002.value);
			logger.info("moneyIn  timeout orders Id:"+orderList.toString());
			logger.info("found"
					+ orderList.size()
					+ "other orders  records, overtime timeout order clean-up work now!");
			Map<MainOrderField, String> map = new HashMap<MainOrderField, String>();

			map.put(MainOrderField.TXN_STA_CD, txnStaCode);
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
			map.put(MainOrderField.TRAN_FINISH_TIME, sf.format(new Date()));
			for (Object obj : orderList) {

				String gopayOrderId = String.valueOf(obj);

				try {
					cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, map);
				} catch (GopayException e) {
					logger.info("update order fail,orderId:" + gopayOrderId);
					e.printStackTrace();
				}
			}
			
		}
		
	}
}
